import os

from Protocol.http_request import HttpRequest
from utils.file_util import FileUtil
from utils.logs_util import logger


class BaseApi:
    app_id = "cli_a16405932fa1500d"
    app_secret = "9HZ6oQq1Y3lCOR0wjsZV2lDFUFzoyetp"
    # 从命令行中获取被执行用例的执行环境
    case_env = os.getenv('case_env')
    # 如果获取到有值，则从配置文件中读取到环境
    if case_env:
        host = FileUtil.read_yaml('env_content')['host'][case_env]
    # 如果从命令行中没有获取到值，则默认将用例在sit环境执行
    else:
        host = FileUtil.read_yaml('env_content')['host']['sit']

    # 获取token
    def feishu_token(self):
        data = {
            "app_id": self.app_id,
            "app_secret": self.app_secret
        }
        url = f"{self.host}/open-apis/auth/v3/tenant_access_token/internal"
        return HttpRequest.send("post", url, json=data)['tenant_access_token']

    # token要传入接口请求的请求头中，单独封装一个请求方式，后续请求不必每次调用feishu_token
    def feishu_send(self, method, url, **data):
        # 打印传入的参数到日志
        logger.info(f"请求url为{url}\n请求方式为{method}\n请求入参为：{data}")
        r = HttpRequest.send(method, url, **data, headers={"Authorization": f"Bearer {self.feishu_token()}"})
        # 打印接口请求返回的内容到日志
        logger.info(f"请求的出参为：{r}")
        return r
